package org.usmile.algorithms.huawei.acm;

import java.util.*;

// https://blog.csdn.net/amos_cloud/article/details/129053794
public class _快递投放问题 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int m = sc.nextInt();
        int n = sc.nextInt();
        sc.nextLine();
        Map<String, String> packageMap = new HashMap<>();
        for (int i = 0; i < m; i++) {
            String[] packageInfo = sc.nextLine().split(" ");
            packageMap.put(packageInfo[0], packageInfo[1] + "->" + packageInfo[2]);
        }
        Map<String, Set<String>> blockedMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            String[] blockedInfo = sc.nextLine().split(" ");
            String road = blockedInfo[0] + "->" + blockedInfo[1];
            Set<String> blockedPackages = new HashSet<>(Arrays.asList(blockedInfo).subList(2, blockedInfo.length));
            blockedMap.put(road, blockedPackages);
        }

        List<String> cantList = new ArrayList<>();
        for (Map.Entry<String, String> entry : packageMap.entrySet()) {
            String pack = entry.getKey();
            String road = entry.getValue();
            if (blockedMap.containsKey(road) && blockedMap.get(road).contains(pack)) {
                cantList.add(pack);
            }
        }
        cantList.sort(String::compareTo);
        System.out.println(String.join(" ", cantList));
    }
}
